var qiniu = require("qiniu");

// domain = 'http://q17dh0vx7.bkt.clouddn.com/';
let bucket = 'sfc-pics';
let putPolicy = new qiniu.rs.PutPolicy({
    scope: bucket,
    returnBody: '{ "code": "0", "msg": "上传成功", "data": { "src": "http://q17dh0vx7.bkt.clouddn.com/$(key)", "title": $(key) }}'
});
let accessKey = 's2dipBr0PFJl7hxJEAfRqsEHlpZaAx_sV5vFg7hb';
let secretKey = '3pIJugfaHh0kaD2nBnvY2eUyiNig6WY6ndVFnjB1';
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
let uploadToken = putPolicy.uploadToken(mac);

let qn = {};

qn.upImg = (key, localFile) => {
    let config = new qiniu.conf.Config();
    config.zone = qiniu.zone.Zone_z0;
    let formUploader = new qiniu.form_up.FormUploader(config);
    let putExtra = new qiniu.form_up.PutExtra();

    return new Promise((resolve, reject) => {
        formUploader.putFile(uploadToken, key, localFile, putExtra, function(respErr, respBody, respInfo) {
            if (respErr) {
                throw respErr
            }
            if (respInfo.statusCode == 200) {
                resolve(respBody);
            } else {
                reject(respInfo);
            }
        })
    })
}

module.exports = {
    uploadFile: qn.upImg
}
